package util

import (
	//"fmt"
	"gin/common"
	sysentity "gin/system/entity"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
)

// ParseJwtToken 解析token得到是自己创建的Claims
func ParseJwtToken(jwtToken string) (*sysentity.JwtClaims, error) {
	var secretKey = []byte("login_user_key")
	var jwtclaim = &sysentity.JwtClaims{}
	//fmt.Println("ParseJwtToken=========================TOKEN:-----------"+jwtToken)
	_, err := jwt.ParseWithClaims(jwtToken, jwtclaim, func(*jwt.Token) (interface{}, error) {
		//得到盐
		return secretKey/*sysentity.Secret*/, nil
	})

	if err != nil {
		if ve, ok := err.(*jwt.ValidationError); ok {
			if ve.Errors&jwt.ValidationErrorMalformed != 0 {
				return nil, sysentity.TokenMalformed
			} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
				// Token is expired
				return nil, sysentity.TokenExpired
			} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
				return nil, sysentity.TokenNotValidYet
			} else {
				return nil, sysentity.TokenInvalid
			}
		}
	}else {
		//fmt.Println("ParseJwtToken==========================解析没有错误")
	}
	return jwtclaim, nil
}

//token校验
// 校验token中间件
func AuthMiddleware() gin.HandlerFunc {
	//	var tokeString = ""
	//var c *gin.Context
	return func(c *gin.Context) {
		// 从请求头中获取token
		tokeString := c.GetHeader("Token")
		//fmt.Println("==================================请求头中的token为：" + tokeString)
		if tokeString == "" {
			c.JSON(http.StatusOK, gin.H{
				"code":    405,
				"message": "必须传递token",
			})
			c.Abort()
			return
		}

		claims, err := ParseJwtToken(tokeString)
		if claims == nil {
			//common.ReturnError(c, 500, "token解析错误,请联系开发人员处理！", "", int64(len("")))
			common.ReturnError(c, 500, "登录状态过期，请重新登录！", "", int64(len("")))
			panic("")
		}

		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code":    1005,
				"message": "token解析错误",
			})
			c.Abort()
			//return
			//common.ReturnError(c, 500, "token解析错误", "", int64(len("")))
		}
		// 从token中解析出来的数据挂载到上下文上,方便后面的控制器使用
		//fmt.Println("===============claims.UID" + claims.Uuid)
		//fmt.Println("===============claims.UserName" + claims.UserName)
		c.Set("Uuid", claims.Uuid)
		c.Set("UserName", claims.UserName)
		c.Next()
	}
}
